package com.fxf.srb.core.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fxf.common.exception.Assert;
import com.fxf.common.result.ResponseEnum;
import com.fxf.srb.base.dto.SmsDTO;
import com.fxf.srb.core.enums.TransTypeEnum;
import com.fxf.srb.core.hfb.FormHelper;
import com.fxf.srb.core.hfb.HfbConst;
import com.fxf.srb.core.hfb.RequestHelper;
import com.fxf.srb.core.mapper.UserBindMapper;
import com.fxf.srb.core.pojo.bo.TransFlowBO;
import com.fxf.srb.core.pojo.entity.TransFlow;
import com.fxf.srb.core.pojo.entity.UserAccount;
import com.fxf.srb.core.mapper.UserAccountMapper;
import com.fxf.srb.core.pojo.entity.UserBind;
import com.fxf.srb.core.service.ITransFlowService;
import com.fxf.srb.core.service.IUserAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fxf.srb.core.service.IUserBindService;
import com.fxf.srb.core.service.IUserInfoService;
import com.fxf.srb.core.util.LendNoUtils;
import com.fxf.srb.rabbitutil.constant.MQConst;
import com.fxf.srb.rabbitutil.service.MQService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户账户 服务实现类
 * </p>
 *
 * @author fxf
 * @since 2021-05-26
 */
@Service
@Slf4j
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements IUserAccountService {

    @Resource
    private UserBindMapper userBindMapper;
    @Resource
    private ITransFlowService iTransFlowService;
    @Resource
    private IUserBindService iUserBindService;
    @Resource
    private IUserInfoService userInfoService;
    @Resource
    private MQService mqService;



    @Override
    public String commitCharge(BigDecimal chargeAmt, Long userId) {

        //获取用户绑定协议号

        QueryWrapper<UserBind> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        UserBind userBind = userBindMapper.selectOne(wrapper);

        Map<String, Object> paramMaps = new HashMap<>();
        paramMaps.put("agent_id", HfbConst.AGENT_ID);
        paramMaps.put("agent_bill_no", LendNoUtils.getNo());
        paramMaps.put("bind_code",userBind.getBindCode());
        paramMaps.put("charge_amt",chargeAmt);
        paramMaps.put("feeAmt", new BigDecimal("0"));
        paramMaps.put("notifyUrl", HfbConst.RECHARGE_NOTIFY_URL);
        paramMaps.put("returnUrl", HfbConst.RECHARGE_RETURN_URL);
        paramMaps.put("timestamp", RequestHelper.getTimestamp());
        String sign = RequestHelper.getSign(paramMaps);
        paramMaps.put("sign",sign);

        String formStr = FormHelper.buildForm(HfbConst.USERBIND_URL,paramMaps);
        return formStr;
    }

    @Override
    @Transactional
    public String notify(Map<String, Object> paramMap) {
        log.info("充值成功：" + JSONObject.toJSONString(paramMap));

        String bindCode = (String) paramMap.get("bind_code");
        String chargeAmt = (String) paramMap.get("charge_amt");


        baseMapper.updateAccount(bindCode, new BigDecimal(chargeAmt), new BigDecimal(0));
//        userAccount.setAmount(userAccount.getAmount()+chargeAmt);

        //增加交易流水
        //TODO
//        iTransFlowService.saveTransFlow();
        String agentBillNo = (String)paramMap.get("agentBillNo");

        //判断流水是否存在，保证接口的幂等性
        if (iTransFlowService.isSaveTransFlow(agentBillNo)){
            log.warn("幂等性返回");
            return "success";
        }
        TransFlowBO transFlowBO = new TransFlowBO(agentBillNo, bindCode, new BigDecimal(chargeAmt), TransTypeEnum.RECHARGE, "充值");



        //发消息
        log.info("发消息");
        String mobile = userInfoService.getMobileByBindCode(bindCode);
        SmsDTO smsDTO = new SmsDTO();
        smsDTO.setMobile(mobile);
        smsDTO.setMessage("充值成功");
        mqService.sendMessage(MQConst.EXCHANGE_TOPIC_SMS, MQConst.ROUTING_SMS_ITEM, smsDTO);


        iTransFlowService.saveTransFlow(transFlowBO);


        return "success";
    }

    /**
     * 获取用户账户余额
     * @param userId
     * @return
     */
    @Override
    public BigDecimal getAccount(Long userId) {

        QueryWrapper<UserAccount> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);

        UserAccount userAccount = baseMapper.selectOne(wrapper);
        BigDecimal amount = userAccount.getAmount();
        return amount;
    }

    @Override
    public String commitWithdraw(BigDecimal fetchAmt, Long userId) {

        //账户可用余额充足：当前用户的余额 >= 当前用户的提现金额
        BigDecimal amount = this.getAccount(userId);//获取当前用户的账户余额
        Assert.isTrue(amount.doubleValue() >= fetchAmt.doubleValue(),
                ResponseEnum.NOT_SUFFICIENT_FUNDS_ERROR);

        String bindCodeByUserId = iUserBindService.getBindCodeByUserId(userId);

        Map<String, Object> pageMaps = new HashMap<>();

        pageMaps.put("agent_id",HfbConst.AGENT_ID);
        pageMaps.put("agent_bill_no",LendNoUtils.getNo());
        pageMaps.put("bind_code",bindCodeByUserId);
        pageMaps.put("fetchAmt", fetchAmt);
        pageMaps.put("feeAmt", new BigDecimal(0));
        pageMaps.put("notifyUrl", HfbConst.WITHDRAW_NOTIFY_URL);
        pageMaps.put("returnUrl", HfbConst.WITHDRAW_RETURN_URL);
        pageMaps.put("timestamp", RequestHelper.getTimestamp());
        String sign = RequestHelper.getSign(pageMaps);
        pageMaps.put("sign", sign);
        //构建自动提交表单
        String formStr = FormHelper.buildForm(HfbConst.WITHDRAW_URL, pageMaps);
        return formStr;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void notifyWithdraw(Map<String, Object> paramMap) {

        log.info("提现成功");
        String agentBillNo = (String) paramMap.get("agent_bill_no");

        boolean saveTransFlow = iTransFlowService.isSaveTransFlow(agentBillNo);
        if (saveTransFlow){
            log.warn("幂等性返回");
            return;
        }

        String bindCode = (String) paramMap.get("bindCode");
        String fetchAmt = (String) paramMap.get("fetch_amt");

        //根据用户账户修改账户金额
        baseMapper.updateAccount(bindCode, new BigDecimal("-" + fetchAmt), new BigDecimal(0));

        TransFlowBO transFlowBO = new TransFlowBO(
                agentBillNo,
                bindCode,
                new BigDecimal(fetchAmt),
                TransTypeEnum.WITHDRAW,
                "提现"
        );

    }

//    @Transactional(rollbackFor = Exception.class)
//    @Override
//    public void notify(Map<String, Object> paramMap) {
//
//        log.info("充值成功：" + JSONObject.toJSONString(paramMap));
//
//            //......
//
//        //发消息
//        log.info("发消息");
//        String mobile = userInfoService.getMobileByBindCode(bindCode);
//        SmsDTO smsDTO = new SmsDTO();
//        smsDTO.setMobile(mobile);
//        smsDTO.setMessage("充值成功");
//        mqService.sendMessage(MQConst.EXCHANGE_TOPIC_SMS, MQConst.ROUTING_SMS_ITEM, smsDTO);
//    }

}
